// 预加载脚本中可以暴露Node.js API给渲染进程
const { contextBridge, ipcRenderer } = require('electron')

// 暴露窗口控制API给渲染进程
contextBridge.exposeInMainWorld('electron', {
  // 窗口控制
  minimizeWindow: () => ipcRenderer.send('window-control', 'minimize'),
  maximizeWindow: () => ipcRenderer.send('window-control', 'maximize'),
  closeWindow: () => ipcRenderer.send('window-control', 'close'),
  
  // 版本信息
  getVersions: () => {
    return {
      node: process.versions.node,
      chrome: process.versions.chrome,
      electron: process.versions.electron
    }
  },
  
  // 日志功能
  log: {
    info: (message) => ipcRenderer.send('log', { level: 'info', message }),
    warn: (message) => ipcRenderer.send('log', { level: 'warn', message }),
    error: (message, error) => {
      const errorObj = error ? { message: error.message, stack: error.stack } : null;
      ipcRenderer.send('log', { level: 'error', message, error: errorObj });
    }
  }
})

// 保留原有的DOM内容替换功能
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
  
  // 设置全局错误捕获
  window.addEventListener('error', (event) => {
    const { message, filename, lineno, colno, error } = event;
    ipcRenderer.send('log', { 
      level: 'error', 
      message: `页面错误: ${message} (${filename}:${lineno}:${colno})`, 
      error: error ? { message: error.message, stack: error.stack } : null 
    });
    // 不阻止默认行为，让错误继续传播
    return false;
  });
  
  // 捕获未处理的Promise拒绝
  window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    ipcRenderer.send('log', { 
      level: 'error', 
      message: `未处理的Promise拒绝: ${reason}`, 
      error: reason instanceof Error ? { message: reason.message, stack: reason.stack } : null 
    });
    // 不阻止默认行为，让错误继续传播
    return false;
  });
})